package com.feihong.yw189.activity.WebInterface;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.AppUtils;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.http.Host;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.utils.ComPareUtils;
import com.feihong.yw189.utils.MyLoginUtils;
import com.feihong.yw189.utils.ToolsUtil;
import com.feihong.yw189.utils.UserLoginInfo;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.JsAccessEntrace;

import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Author wangziheng
 * @ProjectName ywydt
 * @ClassName BaseWebInterface
 * @package com.feihong.yw189.activity.WebInterface
 * @data 2018/11/13 19:37
 * @Describe   ajax交互 方法接收基类
 * @Change
 */
public class BaseWebInterface {

    protected JsAccessEntrace mJsAccessEntrace;
    protected AgentWeb mAgentWeb;
    protected IAjaxCallBack mIAjaxCallBack;
    protected WebView mWebView;
    private String mSuccessMethodName;
    private String mErrorMethodName;
    protected static final String mDefaultSuccessMethodName = "success";
    protected static final String mDefaultErrorMethodName = "error";
    protected Handler mHandler = new Handler(Looper.getMainLooper());
    public BaseWebInterface(AgentWeb agentWeb,WebView webView,IAjaxCallBack ajaxCallBack){
        mWebView = webView;
        mAgentWeb = agentWeb;
        mJsAccessEntrace = agentWeb.getJsAccessEntrace();
        mIAjaxCallBack = ajaxCallBack;
    }

    /**
     * 跳转专用
     * @param str 里面包含有链接(url),参数(data);链接为web要展示的界面链接,data为需要拼接的参数以及token、sign
     */
    @JavascriptInterface
    public void jump(String str){
        HashMap<String,String> mParams = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(str);
        String url = jsonObject.getString("url");
        JSONObject data = jsonObject.getJSONObject("data");
        if(data != null){
            Set<Map.Entry<String, Object>> datas = data.entrySet();
            if(datas.size() > 0){
                Iterator<Map.Entry<String, Object>> iterator = datas.iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, Object> object = iterator.next();
                    mParams.put(object.getKey(), object.getValue() == null ? "" : object.getValue().toString());
                }
            }
        }
        String requestParams = new ComPareUtils.ComPareBuilder().putMap(mParams).create().getSignString();
        StringBuilder stringBuilder = new StringBuilder();
        Set<String> keySet = mParams.keySet();
        if(keySet.size() > 0){
            for(String key : keySet){
                stringBuilder.append("&" + key + "=" + mParams.get(key));
            }
        }
        url = Host.HTTP_HOME + url + "?sign=" +requestParams + stringBuilder.toString()+"&token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken();
        String finalUrl = url;
        mHandler.post(() -> mIAjaxCallBack.jump(finalUrl));
    }

    /**
     * web界面需要原生去请求一个接口(原生请求可以携带sign和token),并将请求结果返回给web界面
     * @param info   info 里面包含有需要请求的接口路径以及相应的参数、成功失败回调的方法名称
     */
    public void ajax(String info){
        try {
            JSONObject jsonObject = JSON.parseObject(info);
            if (jsonObject == null || TextUtils.isEmpty(jsonObject.getString("url"))) {
                if (mJsAccessEntrace != null) {
                    mJsAccessEntrace.quickCallJs("ajaxError('参数不正确！')");
                }
                if (mWebView != null) {
                    mWebView.loadUrl("javascript:ajaxError('参数不正确！')");
                }
                return;
            }
            String url = jsonObject.getString("url");
            String success = jsonObject.getString("success");
            mSuccessMethodName = TextUtils.isEmpty(success) ? mDefaultSuccessMethodName : success;
            String error = jsonObject.getString("error");
            mErrorMethodName = TextUtils.isDigitsOnly(error) ? mDefaultErrorMethodName : error;
            String timeOut = jsonObject.getString("timeout");
            HashMap<String, String> params = new HashMap<>();
            if (jsonObject.containsKey("data")) {
                Set<Map.Entry<String, Object>> datas = jsonObject.getJSONObject("data").entrySet();
                if ( datas.size() > 0) {
                    Iterator<Map.Entry<String, Object>> iterator = datas.iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, Object> object = iterator.next();
                        params.put(object.getKey(), object.getValue() == null ? "" : object.getValue().toString());
                    }
                }
            }
            params.put("token", UserLoginInfo.getUserLoginInfoInstance().getUserToken());
            params.put("time", "" + MyLoginUtils.getCuurrentTime());
            params.put("version",  "and." + AppUtils.getAppVersionName());
            String sign = ToolsUtil.getsignRes("", params);
            params.put("sign", sign);
            int mTimeOut = (TextUtils.isEmpty(timeOut)) ? 0 : Integer.valueOf(timeOut);
            App.getApp().getHttpTools().ajaxPost(url, params, mTimeOut, mRequestCallBack);
        } catch (Exception ex) {
            if (mJsAccessEntrace != null) {
                mJsAccessEntrace.callJs("ajaxError('数据解析错误')");
            }
            if (mWebView != null) {
                mWebView.loadUrl("javascript:ajaxError('数据解析错误！')");
            }
        }
    }
    @JavascriptInterface
    public void go_back(){
        if(!mAgentWeb.back()){
            mIAjaxCallBack.goBack();
        }
    }
    private RequestCallBack<String> mRequestCallBack = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            if (mJsAccessEntrace != null) {
                mJsAccessEntrace.callJs(mSuccessMethodName + "('" + result + "')");
            }
            if (mWebView != null) {
                mWebView.loadUrl("javascript:" + mSuccessMethodName + "('" + result + "')");
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (mJsAccessEntrace != null) {
                mJsAccessEntrace.callJs(mErrorMethodName + "()");
            }
            if (mWebView != null) {
                mWebView.loadUrl("javascript:"+mErrorMethodName+"()");
            }
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };
}
